package com.ruoyi.college.service.impl;

import java.util.*;

import com.ruoyi.college.domain.FirstLevelSubject;
import com.ruoyi.college.domain.SecondLevelSubject;
import com.ruoyi.college.domain.vo.DirectionReturnVo;
import com.ruoyi.college.domain.vo.TrainingSubjectVo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.trainingManagement.domain.TrainingProgramSubject;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.college.mapper.ResearchDirectionMapper;
import com.ruoyi.college.domain.ResearchDirection;
import com.ruoyi.college.service.IResearchDirectionService;

/**
 * 学科研究方向Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-31
 */
@Service
public class ResearchDirectionServiceImpl implements IResearchDirectionService 
{
    @Autowired
    private ResearchDirectionMapper researchDirectionMapper;
    @Autowired
    private SecondLevelSubjectServiceImpl secondLevelSubjectService;
    @Autowired
    private FirstLevelSubjectServiceImpl firstLevelSubjectService;

    /**
     * 查询学科研究方向
     * 
     * @param id 学科研究方向主键
     * @return 学科研究方向
     */
    @Override
    public ResearchDirection selectResearchDirectionById(String id)
    {
        return researchDirectionMapper.selectResearchDirectionById(id);
    }

    /**
     * 查询学科研究方向列表
     * 
     * @param researchDirection 学科研究方向
     * @return 学科研究方向
     */
    @Override
    public List<ResearchDirection> selectResearchDirectionList(ResearchDirection researchDirection)
    {
        return researchDirectionMapper.selectResearchDirectionList(researchDirection);
    }

    /**
     * 新增学科研究方向
     * 
     * @param researchDirection 学科研究方向
     * @return 结果
     */
    @Override
    public int insertResearchDirection(ResearchDirection researchDirection)
    {
        researchDirection.setCreateTime(DateUtils.getNowDate());
        return researchDirectionMapper.insertResearchDirection(researchDirection);
    }

    /**
     * 修改学科研究方向
     * 
     * @param researchDirection 学科研究方向
     * @return 结果
     */
    @Override
    public int updateResearchDirection(ResearchDirection researchDirection)
    {
        researchDirection.setUpdateTime(DateUtils.getNowDate());
        return researchDirectionMapper.updateResearchDirection(researchDirection);
    }

    /**
     * 批量删除学科研究方向
     * 
     * @param ids 需要删除的学科研究方向主键
     * @return 结果
     */
    @Override
    public int deleteResearchDirectionByIds(String[] ids)
    {
        return researchDirectionMapper.deleteResearchDirectionByIds(ids);
    }

    /**
     * 删除学科研究方向信息
     * 
     * @param id 学科研究方向主键
     * @return 结果
     */
    @Override
    public int deleteResearchDirectionById(String id)
    {
        return researchDirectionMapper.deleteResearchDirectionById(id);
    }

    /**
     * 根据培养方案学科列表查询对应的一级学科、二级学科、研究方向名称
     */
    @Override
    public List<TrainingSubjectVo> selectSubjectListByProgramId(List<TrainingProgramSubject> list) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }

        // 步骤1：提取关键ID（区分一级/二级学科，去重处理）
        Set<String> firstSubjectCodeSet = new HashSet<>(); // 4位一级学科代码
        Set<String> secondSubjectCodeSet = new HashSet<>(); // 6位二级学科代码
        Map<String, Set<String>> directionCodeMap = new HashMap<>(); // key:学科ID, value:研究方向编码集合

        for (TrainingProgramSubject item : list) {
            String subjectId = item.getSubjectId();
            String directionId = item.getRescarechDirectionId();

            if (StringUtils.isBlank(subjectId)) {
                continue;
            }

            // 区分一级/二级学科，收集对应代码
            if (subjectId.length() == 4) {
                firstSubjectCodeSet.add(subjectId);
            } else if (subjectId.length() == 6) {
                secondSubjectCodeSet.add(subjectId);
                // 同时收集其对应的一级学科代码（前4位）
                firstSubjectCodeSet.add(subjectId.substring(0, 4));
            }

            // 收集研究方向编码（按学科ID分组）
            if (StringUtils.isNotBlank(directionId)) {
                directionCodeMap.computeIfAbsent(subjectId, k -> new HashSet<>())
                        .add(directionId);
            }
        }

        // 步骤2：批量查询基础数据（调用新生成的Mapper方法）
        // 2.1 查询所有一级学科信息（通过一级学科代码）
        Map<String, FirstLevelSubject> firstLevelMap = new HashMap<>();
        for (String code : firstSubjectCodeSet) {
            List<FirstLevelSubject> firstList = firstLevelSubjectService.selectByFirstSubjectCode(code);
            if (CollectionUtils.isNotEmpty(firstList)) {
                firstLevelMap.put(code, firstList.get(0)); // 假设代码唯一
            }
        }

        // 2.2 查询所有二级学科信息（通过二级学科代码）
        Map<String, SecondLevelSubject> secondLevelMap = new HashMap<>();
        for (String code : secondSubjectCodeSet) {
            List<SecondLevelSubject> secondList = secondLevelSubjectService.selectBySecondSubjectCode(code);
            if (CollectionUtils.isNotEmpty(secondList)) {
                secondLevelMap.put(code, secondList.get(0)); // 假设代码唯一
            }
        }

        // 2.3 查询所有研究方向信息（核心优化点：直接使用subjectId作为关联ID）
        Map<String, ResearchDirection> directionMap = new HashMap<>();
        for (Map.Entry<String, Set<String>> entry : directionCodeMap.entrySet()) {
            String subjectId = entry.getKey(); // 可能是4位（一级）或6位（二级）
            Set<String> directionCodes = entry.getValue();

            // 关键调整：无论一级/二级学科，直接用subjectId作为研究方向的关联ID
            // （根据业务：一级学科时，research_direction表的second_subject_id存4位一级代码）
            String relatedSubjectId = subjectId;

            if (StringUtils.isBlank(relatedSubjectId)) {
                continue;
            }

            // 按“学科ID+方向编码”查询研究方向
            for (String dirCode : directionCodes) {
                ResearchDirection query = new ResearchDirection();
                query.setSecondSubjectId(relatedSubjectId); // 直接用subjectId
                query.setResearchDirectionCode(dirCode);
                List<ResearchDirection> dirList = researchDirectionMapper.selectBySecondSubjectIdAndCode(query);

                if (CollectionUtils.isNotEmpty(dirList)) {
                    directionMap.put(subjectId + "_" + dirCode, dirList.get(0));
                }
            }
        }

        // 步骤3：按学科分组构建VO
        Map<String, TrainingSubjectVo> resultMap = new HashMap<>();
        for (TrainingProgramSubject item : list) {
            String subjectId = item.getSubjectId();
            String directionId = item.getRescarechDirectionId();

            if (StringUtils.isBlank(subjectId)) {
                continue;
            }

            // 初始化VO（去重，同一学科只创建一个VO）
            TrainingSubjectVo vo = resultMap.get(subjectId);
            if (vo == null) {
                vo = new TrainingSubjectVo();
                resultMap.put(subjectId, vo);

                // 填充一级/二级学科信息
                if (subjectId.length() == 4) {
                    // 一级学科招生：只填充一级信息
                    FirstLevelSubject first = firstLevelMap.get(subjectId);
                    if (first != null) {
                        vo.setFirstSubjectCode(first.getFirstSubjectCode());
                        vo.setFirstSubjectName(first.getFirstSubjectName());
                    } else {
                        vo.setFirstSubjectCode(subjectId);
                        vo.setFirstSubjectName("未知一级学科");
                    }
                } else if (subjectId.length() == 6) {
                    // 二级学科招生：填充一级+二级信息
                    String firstCode = subjectId.substring(0, 4);
                    FirstLevelSubject first = firstLevelMap.get(firstCode);
                    SecondLevelSubject second = secondLevelMap.get(subjectId);

                    // 一级学科信息
                    if (first != null) {
                        vo.setFirstSubjectCode(first.getFirstSubjectCode());
                        vo.setFirstSubjectName(first.getFirstSubjectName());
                    } else {
                        vo.setFirstSubjectCode(firstCode);
                        vo.setFirstSubjectName("未知一级学科");
                    }

                    // 二级学科信息
                    if (second != null) {
                        vo.setSecondSubjectCode(second.getSecondSubjectCode());
                        vo.setSecondSubjectName(second.getSecondSubjectName());
                    } else {
                        vo.setSecondSubjectCode(subjectId);
                        vo.setSecondSubjectName("未知二级学科");
                    }
                }

                // 初始化研究方向列表
                vo.setDirectionReturnVoList(new ArrayList<>());
            }

            // 填充研究方向
            if (StringUtils.isNotBlank(directionId)) {
                ResearchDirection direction = directionMap.get(subjectId + "_" + directionId);
                DirectionReturnVo dirVo = new DirectionReturnVo();
                dirVo.setResearchDirectionCode(directionId); // 方向编码
                dirVo.setName(direction != null ? direction.getName() : "未知研究方向"); // 方向名称

                // 去重添加（需确保DirectionReturnVo重写了equals方法）
                if (!vo.getDirectionReturnVoList().contains(dirVo)) {
                    vo.getDirectionReturnVoList().add(dirVo);
                }
            }
        }

        return new ArrayList<>(resultMap.values());
    }

}
